package event

import "sync"

type IEventHandler interface {
	GetEventChannel() *EventChannel
	EventHandler(e IEvent)
}

type EventManager struct {
	sync.Mutex
	eventHandlers 		map[uint16][]IEventHandler
}

func NewEventManager() *EventManager {
	e := new(EventManager)
	e.eventHandlers = make(map[uint16][]IEventHandler,32)
	return e
}

func (e *EventManager) Register(eventId Event_ID,handler IEventHandler) {
	e.Lock()
	defer e.Unlock()

	var hs []IEventHandler
	if hs,_ = e.eventHandlers[uint16(eventId)];hs == nil {
		hs = []IEventHandler{}
	}
	for _,h := range hs {
		if h == handler {
			return
		}
	}
	hs = append(hs,handler)
	e.eventHandlers[uint16(eventId)] = hs
}

func (e *EventManager) UnRegister(eventId Event_ID,handler IEventHandler) {
	e.Lock()
	defer e.Unlock()

	if hs,ok := e.eventHandlers[uint16(eventId)];ok {
		for i:=0;i<len(hs);i++ {
			if hs[i] == handler {
				hs = append(hs[:i],hs[i+1:]...)
				return
			}
		}
	}
}

func (e *EventManager) Notify(eventId Event_ID,data interface{}) {
	e.Lock()
	defer e.Unlock()

	if handlers,ok := e.eventHandlers[uint16(eventId)];ok {
		for _,handler := range handlers {
			handler.GetEventChannel().GetChannel() <- NewEvent(eventId,data)
		}
	}
}